import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken, getRefreshToken, setToken, setRefreshToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // 确保cookie可以被携带
  timeout: 60000 // 请求超时时间
})

// 用于标记是否正在刷新token
let isRefreshing = false
// 存储因token失效而被挂起的请求
let requests = []

// let loading
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    // 判断是否为刷新 token 请求
    if (config.url !== '/api/oauth/user/refresh_token' && store.getters.token) {
      // 让每个请求携带 token
      // ['Authorization'] 是自定义的请求头键
      // 请根据实际情况修改
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.error(error) // for debug
    return Promise.reject(error)
  }
)

// 刷新token的函数
const refreshToken = () => {
  const formData = new FormData()
  formData.append('refresh_token', getRefreshToken())
  return service.post('/api/oauth/user/refresh_token', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }})
}

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // 判断返回对象是否是Blob类型
    if (Object.prototype.toString.call(res) === '[object Blob]') {
      return res
    }

    // 10005: 为非法的用户凭证！
    if (res.code === '10005') {
      const config = response.config
      if (!isRefreshing) {
        isRefreshing = true
        return refreshToken()
          .then(({ data }) => {
            // 更新token
            this.$store.commit('SET_TOKEN', data.access_token)
            this.$store.commit('SET_REFRESH_TOKEN', data.refresh_token)
            setToken(data.access_token)
            setRefreshToken(data.refresh_token)
            // 更新请求头中的token
            config.headers['Authorization'] = 'Bearer ' + data.access_token
            // 重新发起被挂起的请求
            requests.forEach(cb => cb(data.access_token))
            requests = []
            return service(config)
          })
          .catch(err => {
            console.error('刷新token失败', err)
            Message({
              message: '登录已过期，请重新登录',
              type: 'error',
              duration: 5 * 1000
            })
            // 清楚token，跳转到登录页
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
            return Promise.reject(err)
          })
          .finally(() => {
            isRefreshing = false
          })
      } else {
        // 如果正在刷新token，将请求挂起
        return new Promise(resolve => {
          requests.push(token => {
            config.headers['Authorization'] = 'Bearer ' + token
            resolve(service(config))
          })
        })
      }
      // // 提示消息，重新登录
      // Message({
      //   message: res.msg || 'Error',
      //   type: 'error',
      //   duration: 5 * 1000
      // })
      // store.dispatch('user/resetToken').then(() => {
      //   location.reload()
      // })
    }

    // 这里定义正常的返回码为：00000
    if (res.code !== '00000') {
      // 提示错误信息
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      //
      // if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
      //   // to re-login
      //   MessageBox.confirm('您的账户已被注销，您可以取消当前页面或者重新登录！', '退出确认', {
      //     confirmButtonText: '重新登录',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then(() => {
      //     store.dispatch('user/resetToken').then(() => {
      //       location.reload()
      //     })
      //   })
      // }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.error('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
